package com.cakebackoffice;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.*;
import com.cakebackoffice.Model.*;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class FormActivity2 extends Activity {


    public List<ProductType> productTypeList = new ArrayList<ProductType>();                    //la liste des produits à charger dans le listview de gauche
    private List<OrderLine> orderLines = new ArrayList<OrderLine>();                             //la liste des orderLines créées pour l'order, à charger dans le listview de droite
    private List<CatalogCategory> catalogCategories = new ArrayList<CatalogCategory>();          //la liste des catégories de produit
    private List<String> categoriesToString = new ArrayList<String>();           //catalogCategories en string
    private ListView lv1, lv2;
    private Long tamponOrderId;
    private Order tamponOrder;
    private CatalogCategory category = null;


    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.createform2);

        this.category = CatalogCategory.getOne(this, 1l);          //One is ROOOT !
        this.tamponOrderId = getIntent().getExtras().getLong("orderid");
        this.tamponOrder = Order.getOne(this, tamponOrderId);


        getCategories();

        updateSpinner();
        setListviews();
        updateTotal();


    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.editordercontent, menu);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {

        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();


        switch (item.getItemId()) {
            case R.id.button_up:
                ((OrderLine) lv2.getItemAtPosition((int) info.id)).addOne();
                refreshListviews();
                return true;
            case R.id.button_down:
                ((OrderLine) lv2.getItemAtPosition((int) info.id)).removeOne();
                refreshListviews();
                return true;
            case R.id.button_delete:
                ((OrderLine) lv2.getItemAtPosition((int) info.id)).delete();
                refreshListviews();
                return true;
            default:
                return super.onContextItemSelected(item);
        }

    }


    private void updateTotal() {
        TextView totalTTC = (TextView) findViewById(R.id.totalTTC);
        totalTTC.setText("Total : " + this.tamponOrder.getTotalAmountTTC().toString());
    }

    public void onClickButtonMore(View v) {
        for (OrderLine r : orderLines) {
            if (r.getTag().equals(((Button) v).getTag())) {       //On compare les strings avec equals ! sinon on compare juste les références !
                r.addOne();
            }
        }
        refreshListviews();
        Toast.makeText(this, "Un de plus !", Toast.LENGTH_SHORT).show();
    }

    public void onClickButtonLess(View v) {
        for (OrderLine r : orderLines) {
            if (r.getTag().equals(((Button) v).getTag())) {        //On compare les strings avec equals ! sinon on compare juste les références !
                r.removeOne();
            }
        }
        refreshListviews();
        Toast.makeText(this, "Un de moins !", Toast.LENGTH_SHORT).show();
    }

    public Order getTamponOrder() {
        return this.tamponOrder;
    }

    public void setTamponOrder(Order tamponOrder) {
        this.tamponOrderId = tamponOrder.getIdDB();
        this.tamponOrder = tamponOrder;
    }

    //get les orderlines du listview droit
    private void updateOrderlines() {
        try {
            orderLines = getTamponOrder().getOrderLines();
        } catch (Exception e) {
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }


    //get les gatégories et les categories en string
    private void getCategories() {
        this.catalogCategories = CatalogCategory.getAll(this);
        categoriesToString.clear();
        for (CatalogCategory c : catalogCategories) {
            categoriesToString.add(c.getName());
        }
    }

    //générer la liste de typeproduit du listviewgauche
    private void generateProductTypesFromCategory() {
        List<Long> productChilds = new LinkedList<Long>();
        if (category != null) {
            productChilds = category.getChildProductTypeId();
            productTypeList.clear();
        }

        for (Long pid : productChilds) {
            productTypeList.add(ProductType.getOne(this, pid));
        }

        refreshListviews();

    }


    //update du spinner
    private void updateSpinner() {
        //categoriesToString.add("Sélectionnez une catégorie");
        //on récup les catégories
        getCategories();

        //on la met dans le spinner
        Spinner spinner = (Spinner) findViewById(R.id.spinner2);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categoriesToString);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());

    }

    public class MyOnItemSelectedListener implements AdapterView.OnItemSelectedListener {

        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {

            String stringCategory = categoriesToString.get(pos);
            category = null;

            //on récup la bonne catégorie
            for (CatalogCategory c : catalogCategories) {
                if (c.getName().compareToIgnoreCase(stringCategory) == 0) {
                    category = c;
                    break;
                }
            }
            //affichage de la bonne catégorie  dans le listview gauche
            if (category != null) {
                generateProductTypesFromCategory();
            }

        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {
            //To change body of implemented methods use File | Settings | File Templates.
        }
    }


    //Enregistre la commande
    public void save(View v) {

        SendTask sendTask = new SendTask();
        sendTask.execute(new Order[]{this.getTamponOrder()});

    }


    private class SendTask extends SyncTaskManager.SendOrder {
        private SendTask() {
            super(FormActivity2.this);
        }

        @Override
        protected void onPostExecute(Integer i) {
            super.onPostExecute(i);

            if (i == 100) {
                Toast.makeText(this.getContext(), "Commande envoyée au serveur !", Toast.LENGTH_SHORT).show();

                Intent intent = new Intent(this.getContext(), OrderActivity.class);
                startActivity(intent);
            }
        }
    }

    //Annule la commande
    public void cancel(View view) {
        finish();
    }

    private void setListviews() {
        ListAdapter adapterLeft = new ListviewProductListAdapter(this, R.layout.itemproductorderbuilder, productTypeList);
        lv1 = (ListView) findViewById(R.id.listViewProducts);
        lv1.setAdapter(adapterLeft);

        ListAdapter adapterRight = new ListviewOrderListAdapter(this, R.layout.iteminorder, orderLines);
        lv2 = (ListView) findViewById(R.id.listViewOrderContent);
        lv2.setAdapter(adapterRight);

        // Ajout du menu pour les touch long. en fait il marche plus parce que les listview ne sont plus clickable
        //registerForContextMenu(lv2);

        //les listeners de clics
        lv1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                addItemToOrder(position);
                Toast.makeText(FormActivity2.this, "Produit ajouté", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void refreshListviews() {
        ListAdapter adapterLeft = new ListviewProductListAdapter(this, R.layout.itemproductorderbuilder, productTypeList);
        lv1 = (ListView) findViewById(R.id.listViewProducts);
        lv1.setAdapter(adapterLeft);

        updateOrderlines();
        ListAdapter adapterRight = new ListviewOrderListAdapter(this, R.layout.iteminorder, orderLines);
        lv2 = (ListView) findViewById(R.id.listViewOrderContent);
        lv2.setAdapter(adapterRight);

        updateTotal();
    }

    private void addItemToOrder(int position) {
        ProductType p = productTypeList.get(position);
        UnitarySale u = new UnitarySale(p.getLocalPrice(null), p.getVatOrDefault(), p, new Product(p));
        Order o = getTamponOrder();
        o.getUnitarySaleList().add(u);
        //o.saveToDatabase(this);
        refreshListviews();
    }


}




